package com.nuanshui.heatedloan.baseservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.framework.utils.mongo.MongoManager;
import com.nuanshui.heatedloan.baseservice.facade.StatisticService;
import com.nuanshui.heatedloan.baseservice.form.StatisticsForm;
import com.nuanshui.heatedloan.baseservice.model.BrownseRecord;
import com.nuanshui.heatedloan.baseservice.model.BrownseRecord.SubProperty;
import com.nuanshui.heatedloan.baseservice.model.GoodsAttrItem;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.baseservice.model.UserOprationRecord;
import com.nuanshui.heatedloan.baseservice.vo.PostTypeVO;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageSender;
import com.nuanshui.heatedloan.middleware.rabbitmq.message.RabbitmqMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service(ServiceConstant.STATISTICSERVICE)
public class StatisticServiceImpl extends CommonServiceImpl implements StatisticService {
	private static final Logger logger = LoggerFactory.getLogger(StatisticService.class);

	@Autowired
	private RabbitmqMessageSender rabbitmqMessageSender;

	@Autowired
	private MongoManager mongoManager;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


	public void saveRecord(StatisticsForm form)
	{
		rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_STATISTICS,form);
	}

	/**
	 * 将操作记录 记录到mongoDb
	 * 
	 * @param opType
	 *            操作类型
	 * @param userId
	 *            用户ID
	 */
	public void logMongoRecord(String opType, String userId) {
		try {
			LogUtil.info(logger, "----保存到用户 " + opType + " 操作到mongoDB----");
			UserOprationRecord uor = new UserOprationRecord();
			UserAgent userAgent = getUserAgent();
			uor.setUserId(userId);
			uor.setOpTime(sdf.format(new Date()));
			uor.setOpType(opType);
			if(  getRequest() != null ){
			uor.setIpAddress(getRequest().getRemoteAddr());
			if (isFromWechat()) {
				uor.setChannel("wechat");
			} else {
				uor.setChannel(userAgent.getClient());
			}
			}
			
			uor.setSafeToken(userAgent.getSafeToken());
			BasicDBObject basicDBObject = new BasicDBObject(JSON.parseObject(JSON.toJSONString(uor)));
			mongoManager.save(UserOprationRecord.USER_OPRATION_RECORD, basicDBObject);
		} catch (Exception e) {
			LogUtil.error(logger, "mongo记录失败", e);
			e.printStackTrace();

		}

	}

	/**
	 * 保存用户浏览记录到mongoDB
	 * 
	 * @param keyword
	 */
	public void logUserSearchRecord(String keyword,String userId) {
		try {
			LogUtil.info(logger, "----保存到用户搜索记录关键词:" + keyword + " 操作到mongoDB----");
			BrownseRecord brownseRecord = new BrownseRecord();
			brownseRecord.setPrimaryAttribute(keyword);
			brownseRecord.setUserId(userId);
			brownseRecord.setOpTime(sdf.format(new Date()));
			brownseRecord.setWeight(BrownseRecord.SEARCH_WEIGHT);
			BasicDBObject basicDBObject = new BasicDBObject(JSON.parseObject(JSON.toJSONString(brownseRecord)));
			mongoManager.save(BrownseRecord.BRONSE_RECORD, basicDBObject);
		} catch (Exception e) {
			LogUtil.error(logger, "----mongo搜索记录失败----", e);
			e.printStackTrace();
		}
	}

	public void logUserBrownseRecord(List<GoodsAttrItem> list, PostTypeVO postTypeVO, String postId, String userId) {
		try {
			LogUtil.info(logger, "----保存到用户浏览记录 postId:" + postId + " 操作到mongoDB----");
			BrownseRecord brownseRecord = new BrownseRecord();
			brownseRecord.setUserId(userId);
			brownseRecord.setPostId(postId);
			brownseRecord.setPrimaryAttribute(postTypeVO.getName()); // 一级属性 和田玉
			for (GoodsAttrItem goods : list) {
				String attrName = goods.getName();
				if (attrName.equals(SubProperty.texture.getAttrName())) {
					brownseRecord.setTexture(goods.getAttrValue());
				}
				if (attrName.equals(SubProperty.purpose.getAttrName())) {
					brownseRecord.setPurpose(goods.getAttrValue());
				}
				if (attrName.equals(SubProperty.style.getAttrName())) {
					brownseRecord.setStyle(goods.getAttrValue());
				}
				if (attrName.equals(SubProperty.color.getAttrName())) {
					brownseRecord.setColor(goods.getAttrValue());
				}				
			}
			brownseRecord.setWeight(BrownseRecord.BROWSE_WEIGHT);
			brownseRecord.setOpTime(sdf.format(new Date()));
			BasicDBObject basicDBObject = new BasicDBObject(JSON.parseObject(JSON.toJSONString(brownseRecord)));
			mongoManager.save(BrownseRecord.BRONSE_RECORD, basicDBObject);
		} catch (Exception e) {
			LogUtil.error(logger, "----mongo浏览记录失败----", e);
			e.printStackTrace();
		}

	}

}
